package com.sfac.springboot.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebListener
@RestController// 又该注解，@Value("${log.Path}")才生效
public class LogListener implements ServletContextListener {
    private final static Logger LOGGER = LoggerFactory.getLogger(LogListener.class);

   /* @Value("${log.Path}")
    public String logPath;*/

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("=== init log listener=====");
        //获取/var/log 日志文件夹，判断是否存在，如果不存在直接返回
        File file = new File("/var/log");
        if(file == null){
            return;
        }

        //获取当前日期
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDateString = dtf.format(LocalDateTime.now());

        //获取/var/log 下日志文件列表，循环判断文件名称是否包含日期字符串，不包含则删除
        File[] files = file.listFiles();
        for(File temp : files) {
            String name = temp.getName();
            if(!name.contains(currentDateString)){
                temp.delete();
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("=== destroyed log listener=====");

    }
}
